package com.nursinghome.management.service;

import com.nursinghome.management.model.Elderly;
import com.nursinghome.management.model.HealthRecord;
import com.nursinghome.management.repository.HealthRecordRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class HealthRecordService {

    private final HealthRecordRepository healthRecordRepository;

    public HealthRecordService(HealthRecordRepository healthRecordRepository) {
        this.healthRecordRepository = healthRecordRepository;
    }

    public List<HealthRecord> getAllHealthRecords() {
        return healthRecordRepository.findAll();
    }

    public HealthRecord getHealthRecordById(Long id) {
        return healthRecordRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Health record not found with id: " + id));
    }

    public List<HealthRecord> getHealthRecordsByElderly(Elderly elderly) {
        return healthRecordRepository.findByElderlyOrderByRecordDateDesc(elderly);
    }

    public HealthRecord createHealthRecord(HealthRecord healthRecord) {
        return healthRecordRepository.save(healthRecord);
    }

    public HealthRecord updateHealthRecord(HealthRecord healthRecord) {
        HealthRecord existingRecord = healthRecordRepository.findById(healthRecord.getId())
                .orElseThrow(() -> new RuntimeException("Health record not found with id: " + healthRecord.getId()));

        existingRecord.setTemperature(healthRecord.getTemperature());
        existingRecord.setHeartRate(healthRecord.getHeartRate());
        existingRecord.setBloodPressureSystolic(healthRecord.getBloodPressureSystolic());
        existingRecord.setBloodPressureDiastolic(healthRecord.getBloodPressureDiastolic());
        existingRecord.setRespirationRate(healthRecord.getRespirationRate());
        existingRecord.setWeight(healthRecord.getWeight());
        existingRecord.setNotes(healthRecord.getNotes());

        return healthRecordRepository.save(existingRecord);
    }

    public void deleteHealthRecord(Long id) {
        healthRecordRepository.deleteById(id);
    }
}